package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chenenyu.router.annotation.Route;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.SuggestActivityBinding;
import sz.szsmk.citizencard.dialog.SuccessDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.log.L;
import sz.szsmk.citizencard.model.network.bean.response.SuggestMsgRes;
import sz.szsmk.citizencard.mvp.contract.ISuggestContact;
import sz.szsmk.citizencard.mvp.presenter.SuggestPresenter;
import sz.szsmk.citizencard.ui.adapter.SuggestAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.PhotoUtils;
import sz.szsmk.citizencard.util.PubUtils;

import static java.lang.String.valueOf;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/8/9 19:53
 * description:
 */
@Route("suggest")
public class SuggestActivity extends IBaseActivity<SuggestPresenter, SuggestActivityBinding>
        implements ISuggestContact.ISuggestView, View.OnClickListener {

    private String versionName;
    private View inflate;
    private Dialog dialog;
    private TextView getPhoneCamera;
    private TextView getPhoneAlbnm;

    private Bitmap bitmap;
    private File file;
    private String url = Constant.BASE_URL + "app/config/submitUserFeedback";
    private Uri cropImageUri;

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private Uri imageUri;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private String phone;
    private String content;
    private RecyclerView suggestRv;
    private LinearLayout suggestLL;
    private SuggestAdapter adapter;
    private int ivState = 0;

    @Override
    protected int attachLayoutRes() {
        return R.layout.suggest_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);

    }

    @Override
    protected void initViews() {
        ivState = 0;
        suggestRv = (RecyclerView) findViewById(R.id.suggest_rv);
        suggestLL = (LinearLayout) findViewById(R.id.suggest_ll_submit);
        suggestRv.setVisibility(View.GONE);
        dataBinding.title.back.setOnClickListener(this);
        dataBinding.suggestSure.setOnClickListener(this);
        dataBinding.title.settingTitle.setText("意见反馈");
        dataBinding.suggestIv.setOnClickListener(this);
        dataBinding.suggestLook.setOnClickListener(this);
        dataBinding.suggestSubmit.setOnClickListener(this);

        dataBinding.suggestSure.setEnabled(true);

        adapter = new SuggestAdapter(this);
        suggestRv.setAdapter(adapter);
    }

    @Override
    protected void updateViews() {
    }

    @Override
    public void submitSutggetSucc() {
        final SuccessDialog dialog = new SuccessDialog(this, "提交成功");

        dialog.show();
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
                finish();
            }
        }.start();
    }

    @Override
    public void submitSutggetFail() {

    }

    @Override
    public void getReplySucc(SuggestMsgRes response) {
        List<SuggestMsgRes.FeedbackListBean> feedback_list = response.getFeedback_list();
        if (feedback_list != null) {
            if (feedback_list.size() == 0) {

                Toast.makeText(this, "暂无回复数据", Toast.LENGTH_SHORT).show();
                dataBinding.noData.setVisibility(View.VISIBLE);
            } else {
                adapter.setItemData(feedback_list);
                adapter.notifyDataSetChanged();
                dataBinding.noData.setVisibility(View.GONE);
            }
        } else {
//            dataBinding.noData.setV
        }
    }

    @Override
    public void getReplyFail(String msg) {
        PubUtils.popTipOrWarn(this, msg);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.suggest_sure) {
            dataBinding.noData.setVisibility(View.GONE);
            phone = dataBinding.suggestPhone.getText().toString();
            content = dataBinding.suggestContent.getText().toString();
            PackageManager packageManager = getPackageManager();
            String packageName = getPackageName();
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
                versionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (ivState == 0) {
                showLoadingDialog();
                mPresenter.submitSutgget(phone, content, versionName);
            } else {
                dataBinding.suggestSure.setEnabled(false);
                upLoad(phone);
            }
        } else if (id == R.id.suggest_iv) {
            uploadIv();
        } else if (id == R.id.suggest_look) {
            suggestRv.setVisibility(View.VISIBLE);
            suggestLL.setVisibility(View.GONE);
            mPresenter.getSuggestReply();
            dataBinding.suggestLook.setSelected(true);
            dataBinding.suggestSubmit.setSelected(false);
            dataBinding.suggestLine1.setVisibility(View.GONE);
            dataBinding.suggestLine2.setVisibility(View.VISIBLE);
        } else if (id == R.id.suggest_submit) {
            suggestRv.setVisibility(View.GONE);
            suggestLL.setVisibility(View.VISIBLE);
            dataBinding.suggestLook.setSelected(false);
            dataBinding.suggestSubmit.setSelected(true);
            dataBinding.noData.setVisibility(View.GONE);

            dataBinding.suggestLine1.setVisibility(View.VISIBLE);
            dataBinding.suggestLine2.setVisibility(View.GONE);
        }
    }


    private void upLoad(String phone) {
        showLoadingDialog();
        String androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        String access_token = ACache.get(DaggerApplication.getIns()).getAsString("access_token");
        dataBinding.suggestIv.setDrawingCacheEnabled(true);
        Bitmap cache = dataBinding.suggestIv.getDrawingCache();
        File files = compressImage(cache);
//        String access_token = ACache.get(this).getAsString("access_token");
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", access_token);
        params.put("app_info", versionName);
        params.put("device_id", androidId);
        params.put("sign", "32");
        params.put("soft_info", "5236");
        params.put("phone", phone);
        params.put("question_content", content);
        OkHttpClient okHttpClient = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), files);

        String name = files.getName();
        String path = files.getPath();
        builder.addFormDataPart("pic", files.getName(), requestBody);

        if (params != null) {
            for (Map.Entry entry : params.entrySet()) {
                builder.addFormDataPart(valueOf(entry.getKey()), valueOf(entry.getValue()));
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e(Constant.TAG, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                BufferedSource source = body.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();
                String readString = buffer.clone().readString(Charset.forName("UTF-8"));
//                Charset charset = UTF8;
                L.e("响应内容:" + buffer.clone().readString(Charset.forName("UTF-8")));
                L.e(Constant.TAG, response.message());
//                Toast.makeText(SuggestActivity.this, "上传图片成功", Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessage(1);

            }
        });

    }


    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case 1:
                    dismissLoadingDialog();
                    dataBinding.suggestSure.setEnabled(false);
                    dataBinding.suggestIv.refreshDrawableState();
                    final SuccessDialog dialog = new SuccessDialog(SuggestActivity.this, "操作成功");

                    dialog.show();
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                Thread.sleep(1000);//休眠3秒
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            dialog.cancel();
                            finish();
                        }
                    }.start();
                    break;

                case 0:

                    break;
                default:
                    break;
            }
        }
    };

    private void uploadIv() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        inflate = LayoutInflater.from(this).inflate(R.layout.dialog_get_head, null);
        //初始化控件
        getPhoneCamera = (TextView) findViewById(R.id.upload_phone_camera);
        getPhoneAlbnm = (TextView) findViewById(R.id.upload_phone_albnm);

//        choosePhoto.setOnClickListener(this);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        dialogWindow.findViewById(R.id.upload_phone_albnm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
                requestPermissions(SuggestActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new RequestPermissionCallBack() {
                    @Override
                    public void granted() {
                        PhotoUtils.openPic(SuggestActivity.this, CODE_GALLERY_REQUEST);
                    }

                    @Override
                    public void denied() {
                        Toast.makeText(SuggestActivity.this, "部分权限获取失败，正常功能受到影响", Toast.LENGTH_LONG).show();
                    }
                });
            }
        });
        dialogWindow.findViewById(R.id.upload_phone_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
                requestPermissions(SuggestActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new RequestPermissionCallBack() {
                    @Override
                    public void granted() {
                        if (hasSdcard()) {
                            imageUri = Uri.fromFile(fileUri);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                                //通过FileProvider创建一个content类型的Uri
                                imageUri = FileProvider.getUriForFile(SuggestActivity.this, getPackageName()+".fileProvider", fileUri);
                            PhotoUtils.takePicture(SuggestActivity.this, imageUri, CODE_CAMERA_REQUEST);
                        } else {
                            Toast.makeText(SuggestActivity.this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
//                            Log.e("asd", "设备没有SD卡");
                        }
                    }

                    @Override
                    public void denied() {
                        requestPermissions(SuggestActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new RequestPermissionCallBack() {
                            @Override
                            public void granted() {
                                PhotoUtils.openPic(SuggestActivity.this, CODE_GALLERY_REQUEST);
                            }

                            @Override
                            public void denied() {
                                Toast.makeText(SuggestActivity.this, "部分权限获取失败，正常功能受到影响", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });
            }


        });
        dialogWindow.findViewById(R.id.upload_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + "app_icon.png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
//                BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
//            BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        handler.removeCallbacksAndMessages(null);
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }


    public void saveBitmapFile(Bitmap bitmap) {
        file = new File("/mnt/sdcard/CityCard/02.jpg");
//        File file = new File(filePath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int output_X = 480, output_Y = 480;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(this, getPackageName()+".fileProvider", new File(newUri.getPath()));
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        Toast.makeText(SuggestActivity.this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);

                    if (bitmap != null) {
                        showImages(bitmap);

                    }
                    break;


                case 1:         // 子窗口ChildActivity的回传数据

                    break;
            }

        }
    }


    private void showImages(Bitmap bitmap) {
//        dataBinding.userinfoIvIcon.setImageBitmap(bitmap);
        saveBitmapFile(bitmap);
        ivState = 1;
        dataBinding.suggestIv.setImageBitmap(bitmap);
    }


    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

}
